package UdpServerAndClient;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClientTest {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClientTest(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的请求：");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            // 发送
            socket.send(requestPacket);
            // 接收服务器返回响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //转换成字符串形式
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClientTest clientTest = new UdpEchoClientTest("127.0.0.1",4096);
        clientTest.start();
    }
}
